<template>
	<view class="custom-navbar" :style="navbarStyle">
		<!-- 状态栏占位（适配沉浸式） -->
		<view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

		<!-- 导航内容区 -->
		<view class="navbar-content" :style="{ height: navbarHeight + 'px' }">
			<!-- 左侧区域 -->
			<view class="navbar-left" @click.stop="handleLeftClick">
				<slot name="left">
					<!-- 默认左侧按钮：返回 -->
					<view v-if="showBack" class="back-btn">
						<uni-icons type="left" size="22" :color="textColor"></uni-icons>
					</view>
				</slot>
			</view>

			<!-- 中间标题 -->
			<view class="navbar-center">
				<text class="title" :style="{ color: textColor, fontSize: titleSize + 'px' }">{{ title }}</text>
			</view>

			<!-- 右侧区域 -->
			<view class="navbar-right" @click.stop="handleRightClick">
				<slot name="right">
					<!-- 右侧默认插槽（可自定义按钮） -->
				</slot>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		computed
	} from 'vue';

	// 接收父组件参数
	const props = defineProps({
		// 标题文字
		title: {
			type: String,
			default: '页面标题'
		},
		// 是否显示返回按钮
		showBack: {
			type: Boolean,
			default: true
		},
		// 导航栏背景色
		bgColor: {
			type: String,
			default: '#ffffff'
		},
		// 文字颜色
		textColor: {
			type: String,
			default: '#333333'
		},
		// 标题字体大小
		titleSize: {
			type: Number,
			default: 18
		},
		// 导航栏高度（不包含状态栏）
		navbarHeight: {
			type: Number,
			default: 44
		}
	});

	// 状态栏高度（系统自动获取）
	const statusBarHeight = ref(0);

	// 计算导航栏整体样式
	const navbarStyle = computed(() => ({
		backgroundColor: props.bgColor,
		// 适配刘海屏两边安全距离
		paddingLeft: 'env(safe-area-inset-left)',
		paddingRight: 'env(safe-area-inset-right)'
	}));

	// 初始化获取状态栏高度
	onMounted(() => {
		// 获取系统状态栏高度
		const {
			statusBarHeight: sbh
		} = uni.getSystemInfoSync();
		statusBarHeight.value = sbh;
	});

	// 左侧区域点击事件
	const emit = defineEmits(['leftClick', 'rightClick']);
	const handleLeftClick = () => {
		// 默认点击返回按钮时返回上一页
		if (props.showBack ) {
			uni.navigateBack();
		}
		emit('leftClick');
	};

	// 右侧区域点击事件
	const handleRightClick = () => {
		emit('rightClick');
	};
</script>

<style scoped>
	.custom-navbar {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 999;
	}

	.status-bar {
		width: 100%;
	}

	.navbar-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 100%;
		padding: 0 16px;
		box-sizing: border-box;
	}

	.navbar-left,
	.navbar-right {
		width: 44px;
		height: 44px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.navbar-center {
		flex: 1;
		text-align: center;
		overflow: hidden;
	}

	.title {
		display: inline-block;
		max-width: 100%;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		font-weight: 500;
	}

	.back-btn {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
	}
</style>